﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using System.Collections.Generic;
using System.Text;

namespace ConsolidationTool.MasterPage.ControlTemplates.ConsolidationTool.MasterPage
{
    public partial class ARTLeftNavigation : UserControl
    {
        const string TopNavListName = "Left Navigation";
        bool isExpand = false;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindTreeView(null);
            }
        }
        private List<Menu> GetDataSourceXml()
        {
            try
            {
                SPWeb web = SPContext.Current.Web;
                SPList list = web.Lists.TryGetList(TopNavListName);
                if (list != null)
                {
                    const string queryStr = @"<OrderBy><FieldRef Name='ConsolidationTool_ParentId' /><FieldRef Name='ConsolidationTool_Sequence' /></OrderBy>";
                    SPQuery query = new SPQuery();
                    query.Query = queryStr;
                    query.RowLimit = 2000;

                    SPListItemCollection items = list.GetItems(query);
                    List<Menu> menuList = new List<Menu>();
                    foreach (SPListItem item in items)
                    {
                        Menu m = new Menu();
                        m.MenuId = int.Parse(item["ConsolidationTool_MenuId"].ToString());
                        m.ParentId = int.Parse(item["ConsolidationTool_ParentId"].ToString());
                        m.Sequence = int.Parse(item["ConsolidationTool_Sequence"].ToString());
                        m.Title = item["Title"].ToString();
                        m.Url = item["ConsolidationTool_Url"].ToString();
                        menuList.Add(m);
                    }
                    Cache["fs_navigation"] = menuList;
                    return menuList;
                }
            }
            catch (Exception ex)
            {
            }
            return null;
        }

        bool withSelected = false;
        private void BindNode(List<Menu> list, TreeNode node)
        {
            list.FindAll(a => a.ParentId+"" == node.Value).ForEach(c =>
            {
                var secnode = new TreeNode()
                {
                    Text = c.Title,
                    SelectAction = TreeNodeSelectAction.Expand,
                    //    NavigateUrl = "#",
                    Value = c.MenuId + ""
                };
                if (c.Url != "#" && !string.IsNullOrEmpty(c.Url))
                {
                    secnode.NavigateUrl = c.Url;
                    secnode.SelectAction = TreeNodeSelectAction.Select;
                }

                if (!withSelected && Request.RawUrl.ToLower().EndsWith(c.Url.ToLower()))
                {
                    withSelected = true;
                    secnode.Text = string.Format("<span class=\"fs_nav_selected\">{0}</span>", secnode.Text);
                    secnode.Selected = true;
                }

                BindNode(list, secnode);
                node.ChildNodes.Add(secnode);
            });            
        }

        private void BindTreeView(List<Menu> list)
        {
            tvNavigation.Nodes.Clear();

            if (Cache["fs_navigation"] == null)
                list = GetDataSourceXml();
            else
                list = Cache["fs_navigation"] as List<Menu>;
             

            if (list == null) return;

            list.FindAll(p => p.ParentId == 0).ForEach(p =>
            {
                var rootNode = new TreeNode();
                rootNode.Text = p.Title;
                // rootNode.NavigateUrl = "#";
                rootNode.Value = p.MenuId + "";
                rootNode.SelectAction = TreeNodeSelectAction.Expand;

                BindNode(list, rootNode);

                //list.FindAll(a => a.ParentId == p.MenuId).ForEach(c =>
                //{
                //    var secnode = new TreeNode()
                //    {
                //        Text = c.Title,
                //        SelectAction = TreeNodeSelectAction.Expand,
                //        //    NavigateUrl = "#",
                //        Value = c.MenuId + ""
                //    };

                //    list.FindAll(d => d.ParentId == c.MenuId).ForEach(e =>
                //    {

                //        var endNode = new TreeNode()
                //        {

                //            Text = e.Title,
                //            SelectAction = TreeNodeSelectAction.Select,
                //            NavigateUrl = e.Url,
                //            Value = e.MenuId + ""
                //        };

                //        if (!withSelected && Request.RawUrl.EndsWith(e.Url))
                //        {
                //            withSelected = true;
                //            endNode.Text = string.Format("<span class=\"fs_nav_selected\">{0}</span>", endNode.Text);
                //            endNode.Selected = true;
                //        }

                //        list.FindAll(f => f.ParentId == e.MenuId).ForEach(g => {
                //            var endNode1 = new TreeNode()
                //            {

                //                Text = g.Title,
                //                SelectAction = TreeNodeSelectAction.Select,
                //                NavigateUrl = g.Url,
                //                Value = g.MenuId + ""
                //            };

                //            if (!withSelected && Request.RawUrl.EndsWith(g.Url))
                //            {
                //                withSelected = true;
                //                endNode1.Text = string.Format("<span class=\"fs_nav_selected\">{0}</span>", endNode1.Text);
                //                endNode1.Selected = true;
                //            }

                //            endNode.ChildNodes.Add(endNode1);
                //        });

                //        secnode.ChildNodes.Add(endNode);
                //    });

                //    rootNode.ChildNodes.Add(secnode);
                //});

                tvNavigation.Nodes.Add(rootNode);
            });

            tvNavigation.CollapseAll();
            ChangeSelectedStyle(tvNavigation.Nodes);
        }

        private void ChangeSelectedStyle(TreeNodeCollection treeNodeCollection)
        {
            foreach (TreeNode item in treeNodeCollection)
            {
                if (item.ChildNodes.Count > 0)
                    ChangeSelectedStyle(item.ChildNodes);
                else
                {
                    if (item.Selected)
                    {
                        ExpandToCurrentNode(item);
                    }
                }
            }
        }

        private void ExpandToCurrentNode(TreeNode item)
        {
            item.Expand();
            if (item.Parent != null)
                ExpandToCurrentNode(item.Parent);
        }



        [Serializable]
        public class Menu
        {
            public int MenuId { get; set; }
            public int ParentId { get; set; }
            public int Sequence { get; set; }
            public string Title { get; set; }
            public string Url { get; set; }
        }
    }
}
